﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.IO;

namespace NetLib.web
{
    public class HttpGet
    {
        protected static String  GetCharacterSet(string s)
        {
            s = s.ToUpper();
            int start = s.LastIndexOf("CHARSET");
            if (start == -1)
                return "";

            start = s.IndexOf("=", start);
            if (start == -1)
                return "";

            start++;
            s = s.Substring(start).Trim();
            int end = s.Length;

            int i = s.IndexOf(";");
            if (i != -1)
                end = i;
            i = s.IndexOf("\"");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("'");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("/");
            if (i != -1 && i < end)
                end = i;

            return s.Substring(0, end).Trim();
        }

        protected static String GetCharacterSet(byte[] data)
        {
            string s = Encoding.Default.GetString(data);
            return GetCharacterSet(s);
        }

        protected static byte[] ReadStream(Stream s)
        {
            try
            {
                byte[] buffer = new byte[8096];
                using (MemoryStream ms = new MemoryStream())
                {
                    while (true)
                    {
                        int read = s.Read(buffer, 0, buffer.Length);
                        if (read <= 0)
                        {
                            return ms.ToArray();
                        }
                        ms.Write(buffer, 0, read);
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static String downloadPage(String url, out bool success, out String message)
        {
            message = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            try
            {
            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {
                byte[] buffer = null;
                using (Stream s = resp.GetResponseStream())
                {
                    buffer = ReadStream(s);
                }

                string pageEncoding = "";
                Encoding e = Encoding.UTF8;
                if (String.IsNullOrWhiteSpace(resp.ContentEncoding)==false)
                    pageEncoding = resp.ContentEncoding;
                else if (String.IsNullOrWhiteSpace(resp.CharacterSet)==false)
                    pageEncoding = resp.CharacterSet;
                else if (resp.ContentType != "")
                    pageEncoding = GetCharacterSet(resp.ContentType);

                if (String.IsNullOrWhiteSpace(pageEncoding))
                    pageEncoding = GetCharacterSet(buffer);

                if (pageEncoding != "")
                {
                    try
                    {
                        e = Encoding.GetEncoding(pageEncoding);
                    }
                    catch
                    {
                        message=("Invalid encoding: " + pageEncoding);
                    }
                }

                string data = e.GetString(buffer);

                success = true;

                return data;
            }
            }
            catch (Exception e)
            {
                success = false;
                message = e.Message;
            }
            return "";
        }
        public static String process(String url, out bool success, out String message)
        {
            String content = "";
            using (WebClient client = new WebClient())
            {
                try
                {
                    content = client.DownloadString(url);
                    success = true;
                    message = "Success";
                }
                catch (Exception e)
                {
                    message = e.Message;
                    success = false;
                }
            }
            return content;
        }
        protected static void prepareParameter(HttpWebRequest webRequest, Hashtable parameter)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("");
            int sz = parameter.Keys.Count;
            int i = 0;
            foreach (String k in parameter.Keys)
            {
                i++;
                String v = (String)parameter[k];
                sb.Append(k);
                sb.Append("=");
                sb.Append(v);
                if (i < sz)
                    sb.Append("&");
            }
            String data = sb.ToString();
            byte[] dataStream = Encoding.UTF8.GetBytes(data);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = dataStream.Length;

            Stream newStream = webRequest.GetRequestStream();
            // Send the data.
            newStream.Write(dataStream, 0, dataStream.Length);
            newStream.Close();

        }
        public static string requestBig5(string url, Hashtable parameter = null, Hashtable headerset = null)
        {
            string responseStr = null;
            HttpWebResponse webResponse = null;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            if (headerset != null)
            {
                webRequest.KeepAlive = true;
                foreach (String k in headerset.Keys)
                {
                    String v = (String)headerset[k];
                    if ("Referer".Equals(k))
                        webRequest.Referer = v;
                    if ("Host".Equals(k))
                        webRequest.Host = v;

                    if ("User-Agent".Equals(k))
                        webRequest.UserAgent = v;

                    if ("Host".Equals(k))
                        webRequest.Host = v;

                    if ("Accept".Equals(k))
                        webRequest.Accept = v;
                }
            }
            webRequest.Method = "POST";
            webRequest.Timeout = 50000;
            if (parameter != null)
            {
                prepareParameter(webRequest, parameter);
            }
            else
            {
                webRequest.ContentType = "text/html; charset=big5";
            }

            try
            {
                webResponse = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (WebException e)
            {
                responseStr = "Error happen! please try later";
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                //发生异常时把错误信息当作错误信息返回
                responseStr = "Error msg:" + e.Message;

            }
            finally
            {
                if (webResponse != null)
                {
                    //获得网络响应流
                    using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("BIG5")))
                    {
                        responseStr = responseReader.ReadToEnd();//获得返回流中的内容
                    }
                    webResponse.Close();//关闭web响应流
                }
            }
            return responseStr;
        }
    }
}
